package ase.assignment.sts.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ase.assignment.sts.api.HandlerFactoryProxy;
import ase.assignment.sts.api.StockHandler;
import ase.assignment.sts.beans.StockAssertEntity;

public class StockAction extends GenericAction {
	public static final int KEY_SUCCESS = 1;
	public static final int KEY_FAIL = 2;

	public int process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String sAdd = request.getParameter("add");
		String sDelete = request.getParameter("delete");
		String sStockId = request.getParameter("stockId");
		String sStockName = request.getParameter("stockName");
		String sStockAmount = request.getParameter("stockAmount");
		String sStockPrice = request.getParameter("stockPrice");
		String sStockPort = request.getParameter("stockPort");
		if (sStockId.length() == 0) {
			return KEY_FAIL;
		}
		int iStockId = Integer.parseInt(sStockId);

		StockHandler handler = HandlerFactoryProxy.instance().getStockHandler();
		if (sAdd != null) {
			if (sStockName.length() == 0) {
				return KEY_FAIL;
			}
			try {
				if (handler.findById(iStockId) != null) {
					return KEY_FAIL;
				}
				StockAssertEntity entity = new StockAssertEntity(iStockId);
				entity.setPortfolio(Integer.parseInt(sStockPort));
				entity.setName(sStockName);
				entity.setAmount(Integer.parseInt(sStockAmount));
				entity.setInitPrice(Integer.parseInt(sStockPrice));
				handler.create(entity);

				return KEY_SUCCESS;

			} catch (Throwable e) {
				e.printStackTrace();
			}
		} else if (sDelete != null) {
			handler.delete(iStockId);
			return KEY_SUCCESS;
		}
		return KEY_FAIL;
	}
}
